import { defineStore } from "pinia";
import categoryApi from "@/api/category";
import type { CategoryData } from "@/api/category";
import { ElMessage } from "element-plus";

interface CategoryStoreStateData {
  category1List: CategoryData[];
  category1Id: string | number;
  category2List: CategoryData[];
  category2Id: string | number;
  category3List: CategoryData[];
  category3Id: string | number;
}

export const useCategoryStore = defineStore("category", {
  state(): CategoryStoreStateData {
    return {
      category1List: [],
      category1Id: "",
      category2List: [],
      category2Id: "",
      category3List: [],
      category3Id: "",
    };
  },
  actions: {
    async getCategory1List() {
      try {
        const result = await categoryApi.getCategory1();
        this.category1List = result;
        return "ok";
      } catch (error) {
        ElMessage.error("获取一级分类列表失败");
        return Promise.reject(error);
      }
    },

    async getCategory2List() {
      this.category2Id = "";
      this.category3Id = "";
      this.category2List = [];
      this.category3List = [];
      try {
        const result = await categoryApi.getCategory2(
          this.category1Id as number
        );
        this.category2List = result;
        return "ok";
      } catch (error) {
        ElMessage.error("获取二级分类列表失败");
        return Promise.reject(error);
      }
    },
    async getCategory3List() {
      this.category3Id = "";
      this.category3List = [];
      try {
        const result = await categoryApi.getCategory3(
          this.category2Id as number
        );
        this.category3List = result;
        return "ok";
      } catch (error) {
        ElMessage.error("获取三级分类列表失败");
        return Promise.reject(error);
      }
    },
  },
  getters: {},
});